<template>
  <el-dialog title="头像设置" :visible.sync="visible" :append-to-body="true" id="dialog">
    <el-upload :action="url" accept=".jpg, .jpeg, .png" :show-file-list="false" 
    :before-upload="beforeUploadHandle" :on-success="handleSuccess" id="dialog">
      <el-image v-model="iconUrl" :src="iconUrl" style="border: 5px double black;"></el-image>
      <br/>
      <el-button type="success" size="mini">点击上传</el-button>
    </el-upload>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        url: '',
        iconUrl: '',
        userId: '',
        dto: {
          id: '',
          filePath: ''
        }
      }
    },
    methods: {
      // 初始化
      init (iconUrl) {
        this.visible = true
        this.url = this.$http.adornUrl('/admin-interfaces/file/upload')
        this.iconUrl = window.localStorage.getItem('icon_url')
        this.userId = window.localStorage.getItem('user_id')
      },
      // 上传前处理图片尺寸
      beforeUploadHandle (file) {
        return new Promise((resolve, reject) => {
          // 创建一个 Image 对象
          const image = new Image()
          const reader = new FileReader()
          // 读取文件的数据
          reader.readAsDataURL(file)
          // 文件读取成功后进行压缩处理
          reader.onload = (event) => {
            image.src = event.target.result
            // 当图片加载完成后进行压缩
            image.onload = () => {
              const canvas = document.createElement('canvas')
              const context = canvas.getContext('2d')
              // 计算压缩后的尺寸
              const maxWidth = 200 // 设置最大宽度
              const maxHeight = 200 // 设置最大高度
              let width = image.width
              let height = image.height
  
              if (width > height) {
                if (width > maxWidth) {
                  height *= maxWidth / width
                  width = maxWidth
                }
              } else {
                if (height > maxHeight) {
                  width *= maxHeight / height
                  height = maxHeight
                }
              }
              // 设置 canvas 的尺寸
              canvas.width = width
              canvas.height = height
              // 进行图片压缩
              context.drawImage(image, 0, 0, width, height)
              // 将压缩后的图片转为 Blob 格式
              canvas.toBlob((blob) => {
                // 创建一个新的 File 对象，替换上传的文件对象
                const compressedFile = new File([blob], file.name, { type: blob.type })
                // 将处理后的文件传递给上传组件
                resolve(compressedFile)
              }, file.type || 'image/jpeg', 0.9) // 设置压缩质量
            }
          }
          // 如果文件读取失败，则直接传递原始文件
          reader.onerror = () => {
            resolve(file)
          }
        })
      },
      handleSuccess (response) {
        if (response.code === 200) {
          this.iconUrl = response.data.filePath
          this.dto.id = this.userId
          this.dto.filePath = this.iconUrl
          this.$http({
            url: this.$http.adornUrl(`/admin-interfaces/file/updateIcon`),
            method: 'post',
            data: this.dto
          }).then(({data}) => {
            if (data.code === 200 && data.data === true) {
              window.localStorage.setItem('icon_url', this.iconUrl)
              this.$message({
                message: '更换头像成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  location.reload()
                }
              })
            } else {
              this.$message.error(data.message)
            }
          })
        }
      }
    }
  }
</script>
<style>
#dialog{
  width: 50%;
  height: 65%;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}
</style>
